/**
 * Covalent Server Code File
 * 
 * File:        server_main.c
 * Brief:       BRIEF
 * Author:      Chen Kangbing
 * Email:       ckblau@outlook.com
 * Modified:    2021/10/14 15:52:41
 *
 */


#include "server_main.h"
#include "cliarg_helper.h"
#include "log_helper.h"
#include "thread_helper.h"
#include "socket_helper.h"
#include "transaction.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


int server_init(ServerTypeDef *psrv, int argc, char **argv) {
    int rv;

    rv = cliarg_parse_arg(psrv, argc, argv);
    if (rv != 0) {
        return 1;
    }

    rv = log_init(psrv);
    if (rv != 0) {
        return 2;
    }

    rv = socket_init_server(psrv);
    if (rv != 0) {
        return 3;
    }

    rv = thread_init_pool(psrv, transaction_main);
    if (rv != 0) {
        return 4;
    }

    return 0;
}

void server_deinit(ServerTypeDef *psrv) {
    if (!psrv) return;
    socket_deinit_server(psrv);
    log_deinit(psrv);
    free(psrv);
}

int main(int argc, char **argv) {
    ServerTypeDef *psrv;
    psrv = malloc(sizeof(ServerTypeDef));
    if (!psrv) exit(1);
    memset(psrv, 0, sizeof(ServerTypeDef));

    int rv = server_init(psrv, argc, argv);
    if (rv) exit(rv);

    while (1) {
        WorkerTaskTypeDef *ptask;
        ptask = calloc(1, sizeof(WorkerTaskTypeDef));
        if (!ptask) break;

        if (socket_loop_listen(psrv, ptask) != 0) {
            continue;
        }

        task_add(psrv, ptask);
        free(ptask);
    }

    server_deinit(psrv);
    return 0;
}
